<template>
  <div class="category-manage">
    <div class="page-header">
      <h2>分类管理</h2>
      <el-button type="primary" @click="handleCreate">
        <el-icon><Plus /></el-icon>
        新增分类
      </el-button>
    </div>
    
    <el-card>
      <template #header>
        <div class="table-header">
          <span>分类列表</span>
          <div class="header-actions">
            <el-select
              v-model="filterType"
              placeholder="分类类型"
              style="width: 120px; margin-right: 10px;"
              clearable
            >
              <el-option label="全部类型" value="" />
              <el-option label="影片分类" value="movie" />
              <el-option label="资讯分类" value="news" />
            </el-select>
            <el-input
              v-model="searchKeyword"
              placeholder="搜索分类名称"
              style="width: 200px; margin-right: 10px;"
              clearable
            />
            <el-button @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="categoryList" v-loading="loading">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="name" label="分类名称" width="150" />
        <el-table-column prop="description" label="分类描述" min-width="200" />
        <el-table-column prop="type" label="分类类型" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.type === 'movie' ? 'primary' : 'success'">
              {{ scope.row.type === 'movie' ? '影片分类' : '资讯分类' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="itemCount" label="内容数量" width="100" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status ? 'success' : 'danger'">
              {{ scope.row.status ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="scope.row.status ? 'danger' : 'success'"
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              size="small" 
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 分类编辑对话框 -->
    <el-dialog
      v-model="categoryDialogVisible"
      :title="categoryDialogTitle"
      width="500px"
    >
      <el-form :model="categoryForm" label-width="80px" :rules="categoryRules" ref="categoryFormRef">
        <el-form-item label="分类名称" prop="name">
          <el-input 
            v-model="categoryForm.name" 
            placeholder="请输入分类名称" 
            maxlength="20" 
            show-word-limit 
            @input="generateSlugFromName" 
          />
        </el-form-item>
        <el-form-item label="分类标识" prop="slug">
          <el-input v-model="categoryForm.slug" placeholder="请输入分类标识（英文或数字）" maxlength="50" show-word-limit />
          <div style="font-size: 12px; color: #666; margin-top: 5px;">
            用于URL路径，如：action-movies
          </div>
        </el-form-item>
        <el-form-item label="分类描述" prop="description">
          <el-input 
            v-model="categoryForm.description" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入分类描述" 
            maxlength="100" 
            show-word-limit 
          />
        </el-form-item>
        <el-form-item label="分类类型" prop="type">
          <el-radio-group v-model="categoryForm.type">
            <el-radio label="movie">影片分类</el-radio>
            <el-radio label="news">资讯分类</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="categoryForm.status" active-text="启用" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="categoryDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCategorySubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { categoryService } from '../../services/categoryService'

const loading = ref(false)
const submitLoading = ref(false)
const searchKeyword = ref('')
const filterType = ref('')
const categoryList = ref([])
const categoryDialogVisible = ref(false)
const categoryDialogTitle = ref('新增分类')
const categoryFormRef = ref()

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const categoryForm = reactive({
  id: null,
  name: '',
  slug: '',
  description: '',
  type: 'movie',
  status: true
})

const categoryRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '分类名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  slug: [
    { required: true, message: '请输入分类标识', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9-]+$/, message: '分类标识只能包含字母、数字和横线', trigger: 'blur' },
    { min: 2, max: 50, message: '分类标识长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择分类类型', trigger: 'change' }
  ],
  description: [
    { max: 100, message: '分类描述不能超过 100 个字符', trigger: 'blur' }
  ]
}

// 加载分类列表
const loadCategoryList = async () => {
  try {
    loading.value = true
    
    // 如果有搜索关键词或类型筛选，使用搜索接口
    if (searchKeyword.value || filterType.value) {
      const response = await categoryService.searchCategories(searchKeyword.value, filterType.value)
      categoryList.value = response.data || []
      pagination.total = categoryList.value.length
    } else {
      // 否则获取所有分类
      const response = await categoryService.getAllCategories()
      const allCategories = response.data || []
      
      // 前端分页
      const startIndex = (pagination.current - 1) * pagination.size
      const endIndex = startIndex + pagination.size
      categoryList.value = allCategories.slice(startIndex, endIndex)
      pagination.total = allCategories.length
    }
  } catch (error) {
    console.error('加载分类列表失败:', error)
    ElMessage.error('加载分类列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadCategoryList()
}

const handleReset = () => {
  searchKeyword.value = ''
  filterType.value = ''
  pagination.current = 1
  loadCategoryList()
}

// 根据分类名称自动生成slug
const generateSlugFromName = () => {
  if (!categoryForm.slug || categoryForm.slug === '') {
    // 只有当slug为空时才自动生成
    const slug = categoryForm.name
      .toLowerCase()
      .replace(/[^\w\u4e00-\u9fa5]+/g, '-') // 替换非字母数字汉字为横线
      .replace(/^-+|-+$/g, '') // 去除首尾横线
      .replace(/--+/g, '-') // 将多个横线替换为单个
      .substring(0, 50) // 限制长度
    
    categoryForm.slug = slug
  }
}

const handleCreate = () => {
  categoryDialogTitle.value = '新增分类'
  Object.assign(categoryForm, {
    id: null,
    name: '',
    slug: '',
    description: '',
    type: 'movie',
    status: true
  })
  categoryDialogVisible.value = true
  
  // 清除表单验证
  nextTick(() => {
    if (categoryFormRef.value) {
      categoryFormRef.value.clearValidate()
    }
  })
}

const handleEdit = (row) => {
  categoryDialogTitle.value = '编辑分类'
  Object.assign(categoryForm, { ...row })
  categoryDialogVisible.value = true
  
  // 清除表单验证
  nextTick(() => {
    if (categoryFormRef.value) {
      categoryFormRef.value.clearValidate()
    }
  })
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除分类 "${row.name}" 吗？删除后无法恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await categoryService.deleteCategory(row.id)
    ElMessage.success('删除成功')
    loadCategoryList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除分类失败:', error)
      ElMessage.error('删除分类失败')
    }
  }
}

const handleToggleStatus = async (row) => {
  try {
    const action = row.status ? '禁用' : '启用'
    await ElMessageBox.confirm(
      `确定要${action}分类 "${row.name}" 吗？`,
      `${action}确认`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用API更新分类状态
    await categoryService.updateCategoryStatus(row.id, !row.status)
    ElMessage.success(`${action}成功`)
    loadCategoryList() // 重新加载列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新分类状态失败:', error)
      ElMessage.error(`${action}失败`)
    }
  }
}

const handleCategorySubmit = async () => {
  try {
    // 表单验证
    await categoryFormRef.value.validate()
    
    submitLoading.value = true
    
    if (categoryForm.id) {
      // 编辑分类
      await categoryService.updateCategory(categoryForm.id, categoryForm)
      ElMessage.success('编辑分类成功')
    } else {
      // 新增分类
      await categoryService.createCategory(categoryForm)
      ElMessage.success('新增分类成功')
    }
    
    categoryDialogVisible.value = false
    loadCategoryList()
  } catch (error) {
    if (error && error.errors) {
      // 表单验证错误，不显示错误消息
      return
    }
    console.error('保存分类失败:', error)
    ElMessage.error('保存分类失败')
  } finally {
    submitLoading.value = false
  }
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadCategoryList()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadCategoryList()
}

onMounted(() => {
  loadCategoryList()
})
</script>

<style scoped>
.category-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>